import Vue from 'vue'
async function Upload(options) {
  const params = await uni.uploadFile({
    header: Upload.mergeHeader(),
    ...options
  })
  if (!params.length) return Upload.errow('服务器错误，请截图联系客服处理')
  if (params.length == 1) return Upload.errow(params[0].errMsg)
  let {
    statusCode,
    data = {}
  } = params[1]
  if (statusCode !== 200) return Upload.errow(`服务器错误，错误码：${statusCode}，请截图联系客服处理`)
  data = JSON.parse(data)
  if (data.code == 401) return Upload.refresh(options)
  if (data.code !== 200) return Upload.errow(data.message || `服务器错误，错误码：${data.code}，请截图联系客服处理`)
  return data
}

Upload.refresh = async function (options) {
  const code = await Vue.prototype.$store.dispatch('refreshToken');
  let data = {
    code: 0,
    data: null
  }
  if (code == 200) data = await Upload[options.method](options);
  return data
};

Upload.mergeHeader = function () {
  const header = {}
  if (Vue.prototype.$store.getters.token) {
    header['Authori-zation'] = `TOKEN_USER:${Vue.prototype.$store.getters.token}`
  }
  return header
}

Upload.errow = function (msg) {
  Vue.prototype.$dialog({ content: msg })
  return {
    code: 0,
    data: null
  }
}

export default Upload